package com.yin.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 基本买票例子
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        Ticket02 ticket02 = new Ticket02();
        new Thread(() -> {
            for (int i = 1; i < 60; i++) {
                ticket02.saleTicket();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i < 60; i++) {
                ticket02.saleTicket();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 1; i < 60; i++) {
                ticket02.saleTicket();
            }
        }, "C").start();
    }
}


// Lock
class Ticket02 {
    // 属性、方法
    private int ticketNum = 50;

    Lock lock1 = new ReentrantLock();



    // 买票的方式
    public synchronized void saleTicket() {
        lock1.lock();

        try {
            if (ticketNum > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (ticketNum--) + "张票,剩余：" + ticketNum);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock1.unlock();
        }
    }
}
